package com.ruoyi.report.service.impl.processor;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HttpUtil;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import com.opencsv.bean.HeaderColumnNameMappingStrategy;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.UtilException;
import com.ruoyi.report.domain.csv.BuyBoxReportCsv;
import com.ruoyi.report.domain.csv.CpaReportCsv;
import com.ruoyi.report.service.ReportProcessor;
import com.ruoyi.walmart.domain.auth.ShopAuth;
import lombok.extern.log4j.Log4j2;

import java.io.*;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

@Log4j2
public class CpaReportProcessor implements ReportProcessor<CpaReportCsv> {
	@Override
	public List<CpaReportCsv> processFileFromURL(String url, String reportType, ShopAuth shopAuth, String requestId, String downloadsPath) {
		// 文件下载与解压逻辑
		String path = downloadsPath;
		String prefix = UUID.randomUUID() + "-" + reportType;
		String fileName = prefix + ".zip";
		File file = new File(path + fileName);
		HttpUtil.downloadFile(url, file);

		ZipFile zipFile = null;
		BufferedInputStream inputStream = null;
		try {
			zipFile = new ZipFile(file);
			inputStream = FileUtil.getInputStream(file);
		} catch (Exception e) {
			e.printStackTrace();
		}

		try (ZipInputStream zipStream = new ZipInputStream(inputStream, CharsetUtil.defaultCharset())) {
			ZipEntry zipEntry;
			// 循环读取压缩包里面的文件
			while (null != (zipEntry = zipStream.getNextEntry())) {
				if (!zipEntry.isDirectory()) {
					String name = zipEntry.getName();
					if (name.endsWith("csv")) {
						BufferedReader br = new BufferedReader(new InputStreamReader(zipFile.getInputStream(zipEntry)));
						// 打印 CSV 每一行内容，便于调试
//						String line;
//						while ((line = br.readLine()) != null) {
//							// 清理反斜杠和不匹配的引号
//							line = line.replaceAll("\\\\", "");  // 删除多余的反斜杠
//							line = line.replaceAll("\"{2}", "\"");  // 替换双引号为单个引号
//							line = line.trim();  // 去除行首尾的空格
//
//							// 打印每行内容，帮助调试
//							System.out.println("Parsing CSV line: " + line);
//						}
						CsvToBean<CpaReportCsv> csvToBean = null;
						try {
							HeaderColumnNameMappingStrategy<CpaReportCsv> strategy = new HeaderColumnNameMappingStrategy<>();
							strategy.setType(CpaReportCsv.class);
							// 创建一个新的 CSVReader 实例并解析文件
							br = new BufferedReader(new InputStreamReader(zipFile.getInputStream(zipEntry)));  // 新建 BufferedReader
							csvToBean = new CsvToBeanBuilder<CpaReportCsv>(br)
									.withMappingStrategy(strategy)
									.withSeparator(',')
									.withQuoteChar('"')
									.withSkipLines(0)  // 可以跳过无效或错误的行
									.withIgnoreLeadingWhiteSpace(true)  // 忽略行前的空格
									.build();
							List<CpaReportCsv> reportCsvs = csvToBean.parse();
							return reportCsvs;
						} catch (Exception e) {
							log.error("error :{}", e.getMessage());
							throw new ServiceException(e.getMessage());
						} finally {
							file.delete();
						}
					}
				}
			}
			// 如果没有找到CSV文件，返回一个空的报告项目列表
			return Collections.emptyList();
		} catch (IOException e) {
			throw new UtilException(e);
		} finally {
			IoUtil.close(inputStream);
		}
	}
}
